package com.work.chat.custom.server.server.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.work.chat.common.eums.BizCodeEnum;
import com.work.chat.common.util.AESUtil;
import com.work.chat.custom.server.config.exception.BizException;
import com.work.chat.custom.server.config.model.UserInfo;
import com.work.chat.custom.server.mapper.UserMapper;
import com.work.chat.custom.server.pojo.dto.UserLoginInfoDTO;
import com.work.chat.custom.server.pojo.entity.User;
import com.work.chat.custom.server.pojo.vo.UserInfoVO;
import com.work.chat.custom.server.pojo.vo.UserLoginInVO;
import com.work.chat.custom.server.server.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Value("${ase.key}")
    private String aseKey;
    @Value("${chat.jwt.duration-in-minute}")
    private Long durationInMinute;
    @Value("${chat.jwt.secret-key}")
    private String secretKey;

    @Override
    public UserLoginInVO loginIn(UserLoginInfoDTO userLoginInfoDTO) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.<User>lambdaQuery()
                .eq(User::getUsername,userLoginInfoDTO.getUsername());
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        if (ObjectUtils.isEmpty(user))
        {
            throw new BizException(BizCodeEnum.NOT_USERNAME_ERROR);
        }
        if (StringUtils.isBlank(user.getPassword()))
        {
            throw new BizException(BizCodeEnum.USER_ERROR);
        }
        String encrypt = AESUtil.encrypt(aseKey, userLoginInfoDTO.getPassword());
        if (!StringUtils.equals(user.getPassword(),encrypt))
        {
            throw new BizException(BizCodeEnum.PASSWORD_ERROR);
        }
        Map<String, Object> claims = new HashMap<>();
        UserInfo userInfo = UserInfo.builder()
                .userId(user.getId())
                .build();
        claims.put("userInfo", JSON.toJSONString(userInfo));
        String jwt = Jwts.builder()
                //header
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + durationInMinute * 1000 * 60))
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user,userInfoVO);
        userInfoVO.setPassword("");
        return  UserLoginInVO.builder()
                .userInfoVO(userInfoVO)
                .token(jwt)
                .build();
    }
}
